<template>
  <view class="tabs">
    <view class="tabs-wrapper">
      <view
        v-for="(tab, index) in tabs"
        :key="index"
        class="tab-item"
        :class="{ active: index === activeIndex }"
        @click="changeTab(index)"
        id="tab"
      >
        {{ tab }}
      </view>
      <view class="slider" :style="sliderStyle"></view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, nextTick } from 'vue'

const tabs = ['Following', 'Discover', 'Nearby']
const activeIndex = ref(0)
const sliderStyle = reactive({
  width: '0px',
  left: '0px',
})

// 更新滑块样式
const updateSlider = () => {
  // 延迟执行，确保页面渲染完成
  setTimeout(() => {
    const query = uni.createSelectorQuery().in(this)
    query
      .selectAll('#' + id)
      .boundingClientRect((res) => {
        if (res[activeIndex.value]) {
          const currentTab = res[activeIndex.value]
          sliderStyle.width = `${currentTab.width}px`
          sliderStyle.left = `${currentTab.left}px`
        }
      })
      .exec()
  }, 100) // 延迟 100ms
}

// 初始化时更新滑块
updateSlider()

// 切换标签
const changeTab = (index) => {
  activeIndex.value = index
  updateSlider()
}
</script>

<style scoped>
.tabs {
  position: relative;
}

.tabs-wrapper {
  position: relative;
  display: flex;
}

.tab-item {
  padding: 10px 20px;
  cursor: pointer;
}

.tab-item.active {
  font-weight: bold;
}

.slider {
  position: absolute;
  bottom: 0;
  height: 4px;
  background-color: #007bff;
  transition: all 0.3s ease;
}
</style>
